package com.ja.openchat.views;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.ui.MainActivity;
import com.ja.openchat.ui.contact.EditUserProfileActivity;
import com.ja.openchat.ui.contact.OnContactChatInfoListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.util.XPopupUtils;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.config.AppConfigInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.OrgUserInfo;
import com.zy.openchat.core.model.user.UserFullInfo;
import com.zy.openchat.core.model.user.UserInfo;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;

import androidx.annotation.NonNull;

public class ChatUserMenuDialog extends BaseBottomDialog{

    private final UserInfo user;
    private final OnItemClickListner listner;
    private boolean toShowInvidePath;//邀请来源
    private boolean blockContact;//是否显示用户账号

    private ChatInfo mChatInfo;
    private UserFullInfo userFullInfo;

    private TextView blockedSwitch;
    private TextView deleteLayout;
    private TextView addLayout;


    public ChatUserMenuDialog(@NonNull Context context, UserInfo user, boolean blockContact,ChatInfo mChatInfo, OnItemClickListner listner) {
        super(context);
        this.user = user;
        this.blockContact = blockContact;
        this.listner = listner;
        this.mChatInfo = mChatInfo;
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.dialog_chat_user_menu_view;
    }


    @Override
    protected void onCreate() {
        super.onCreate();
        blockedSwitch = findViewById(R.id.blockedSwitch);
        deleteLayout = findViewById(R.id.deleteLayout);
        addLayout = findViewById(R.id.addLayout);

        if(user != null){
            requestOrgUserInfo();
            syncUserFullInfo();

//            requestChatInfo(new OnContactChatInfoListener() {
//                @Override
//                public void onResult(ChatInfo chatInfo) {
//                    mChatInfo = chatInfo;
//                }
//            });

        }
        findViewById(R.id.tv_cancel).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        deleteLayout.setOnClickListener(v -> {
            clickDelete();
        });

        addLayout.setOnClickListener(v -> {
            clickAdd();
        });

    }

    private void requestChatInfo(OnContactChatInfoListener listener){
        ChatInfo chatInfo = null;
        if(chatInfo!=null){
            listener.onResult(chatInfo);
        }else if(user!=null){
            TelegramManager.getTelegramManager().createPrivateChat(getContext(), user.id, new TgResultBlock<ChatInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                    if (obj != null) {
                        listener.onResult(obj);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                }
            });
        }else{
            listener.onResult(chatInfo);
        }
    }

    private void syncUserFullInfo() {
        TelegramManager.getTelegramManager().requestContactFullInfo(getContext(), mChatInfo.id, new TgResultBlock<UserFullInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, UserFullInfo obj) {
                if (obj != null) {
                    userFullInfo = obj;
                    resetUI();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }

    public void resetUI() {
        if (userFullInfo != null) {
            blockedSwitch.setText(userFullInfo.is_blocked ? getContext().getString(R.string.remove_blacklist) : getContext().getString(R.string.join_black_list));
        }
        blockedSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                blockSwitchClick();
            }
        });
        if (user != null) {
            if (blockContact) {
                deleteLayout.setVisibility(View.GONE);
                addLayout.setVisibility(View.GONE);
            } else {
                deleteLayout.setVisibility(View.VISIBLE);
                addLayout.setVisibility(View.VISIBLE);
                if (user.is_contact) {
                    addLayout.setVisibility(View.GONE);
                } else {
                    if (!canAddFriend()) {
                        addLayout.setVisibility(View.GONE);
                    }
                    deleteLayout.setVisibility(View.GONE);
                }
            }
        }
    }

    /**
     * 黑名单操作
     */
    private void blockSwitchClick() {
        if (userFullInfo == null) {
            resetUI();
            syncUserFullInfo();
            return;
        }
        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        dialog.setTitle(R.string.dialog_title_tip).setMessage(userFullInfo.is_blocked ? getContext().getString(R.string.remove_black_list_question) : getContext().getString(R.string.join_black_list_question));
        dialog.setPositiveButton(R.string.dialog_ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        blockUser();
                    }
                });
        dialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                resetUI();
            }
        });
        dialog.show();
    }

    private void blockUser() {
        showProgress();
        TelegramManager.getTelegramManager().blockUser(getContext(), mChatInfo.id, !userFullInfo.is_blocked, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getContext().getString(R.string.request_error) + obj.errString);
                    resetUI();
                } else {
                    userFullInfo.is_blocked = !userFullInfo.is_blocked;
                    resetUI();
                    //黑名单操作成功
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getContext().getString(R.string.request_error));

            }
        });
    }
    private boolean canAddFriend() {
        AppConfigInfo info = AppConfigInfo.getAppConfigInfo();
        if (info != null) {
            if (info.onlyWhiteAddFriend) {
                return orgUserInfo != null ? orgUserInfo.isInternal : false;
            }
        }
        return true;
    }

    private OrgUserInfo orgUserInfo;
    public void requestOrgUserInfo() {
        if (user != null) {
            TelegramManager.getTelegramManager().requestOrgContactInfo(getContext(), user.id, new TgResultBlock<OrgUserInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, OrgUserInfo obj) {
                    if (obj != null) {
                        orgUserInfo = obj;
                        resetUI();
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                }
            });
        }
    }

    private void clickAdd() {//添加好友
        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        dialog.setTitle(R.string.dialog_title_tip).setMessage(String.format(getContext().getString(R.string.want_add_somebody_as_friend), user.displayName()));
        dialog.setPositiveButton(R.string.dialog_ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        doAddContact();
                    }
                });
        dialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
    private void doAddContact() {
        showProgress();
        TelegramManager.getTelegramManager().addContact(getContext(), user, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getContext().getString(R.string.request_error) + obj.errString);
                } else {
                    showErrorTip(String.format(getContext().getString(R.string.somebody_added_friends), user.displayName()));
                    TelegramManager.getTelegramManager().sendBeFriendMessage(getContext(), user.id, new TgResultBlock<TgResponse>() {
                        @Override
                        public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                        }

                        @Override
                        public void onTimeout(Map<String, Object> request) {
                        }
                    });
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getContext().getString(R.string.request_error));
            }
        });
    }

    private void clickDelete() {//删除好友
        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        dialog.setTitle(R.string.dialog_title_tip).setMessage(String.format(getContext().getString(R.string.want_delete_friend), user.displayName()));
        dialog.setPositiveButton(R.string.dialog_ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        doDeleteContact();
                    }
                });
        dialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void doDeleteContact() {
        showProgress();
        TelegramManager.getTelegramManager().deleteContact(getContext(), user.id, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getContext().getString(R.string.request_error) + obj.errString);
                } else {
                    showErrorTip(String.format(getContext().getString(R.string.removed_friends_list), user.displayName()));
                    getContext().startActivity(new Intent(getContext(), MainActivity.class));
                    listner.clickPostion(0,null);
                    dismiss();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getContext().getString(R.string.request_error));
            }
        });
    }

    @Override
    protected void onShow() {
        super.onShow();
    }

    @Override
    protected void onDismiss() {
        super.onDismiss();
    }

    @Override
    protected int getMaxHeight() {
        return (int) (XPopupUtils.getAppHeight(getContext()) * 0.98f);
    }


    public interface OnItemClickListner {
        void clickPostion(int position,ChatInfo postion);
    }

}
